﻿Imports BUS
Imports DTO
Imports System.Drawing.Printing

Public Class frmTraCuuAcQuy
    Private aqController As AcQuyBUS
    Private _aq As AcquyDTO
    Private indexGr As Integer = 0
    Private sListAQuy As New List(Of AcquyDTO)
    Public sListAQuySelect As New List(Of Integer)
    Public dataAcQuy As New DataTable

    '------------------------------------------------------'
    '                 Các hàm xử lý phụ                   '
    '------------------------------------------------------'
    Private Sub LockText(ByVal b As Boolean)
        txtCongSuatMin.ReadOnly = b
        txtCongSuatMax.ReadOnly = b
        txtDienApMin.ReadOnly = b
        txtDienApMax.ReadOnly = b
        txtGiaMin.ReadOnly = b
        txtGiaMax.ReadOnly = b
        If (b = True) Then
            txtCongSuatMin.ForeColor = Color.Black
            txtCongSuatMax.ForeColor = Color.Black
            txtDienApMin.ForeColor = Color.Black
            txtDienApMax.ForeColor = Color.Black
            txtGiaMax.ForeColor = Color.Black
            txtGiaMin.ForeColor = Color.Black
        End If
    End Sub

    Private Sub BlockButton(ByVal t As Control, ByVal h As Control, Optional ByVal capdo As Byte = 0)
        Select Case capdo
            Case 0
                t.Enabled = True
                h.Enabled = True
            Case 1
                t.Enabled = False
                h.Enabled = False
        End Select
    End Sub

    Private Sub ReSet()
        txtMaPin.Text = ""
        txtTenPin.Text = ""
        cbLoaiPin.SelectedIndex = -1
        txtHangSX.Text = ""
        txtCongSuatMin.Text = ""
        txtCongSuatMax.Text = ""
        txtDienApMin.Text = ""
        txtDienApMax.Text = ""
        txtGiaMin.Text = ""
        txtGiaMax.Text = ""
    End Sub

    Private Function SelectNameLoai(ByVal idLoai As Integer)
        Dim sListName As List(Of LoaiAcquyDTO) = aqController.SelectNameLoai(idLoai)
        Return sListName(0).TenLoai
    End Function

    Private Sub LoadGrid()
        aqController = New AcQuyBUS()
        dgvDuLieuThem.Rows.Clear()
        For i As Integer = 0 To sListAQuy.Count - 1
            dgvDuLieuThem.Rows.Add()
            dgvDuLieuThem.Rows.Item(i).Cells(0).Value = sListAQuy(i).MaAcQuy
            dgvDuLieuThem.Rows.Item(i).Cells(1).Value = sListAQuy(i).TenAcQuy
            dgvDuLieuThem.Rows.Item(i).Cells(2).Value = sListAQuy(i).HangSanXuat
            dgvDuLieuThem.Rows.Item(i).Cells(3).Value = SelectNameLoai(Val(sListAQuy(i).MaLoai))
            dgvDuLieuThem.Rows.Item(i).Cells(4).Value = sListAQuy(i).MaLoai
            dgvDuLieuThem.Rows.Item(i).Cells(5).Value = sListAQuy(i).DongDien.ToString() + " Ah"
            dgvDuLieuThem.Rows.Item(i).Cells(6).Value = sListAQuy(i).DienAp
            dgvDuLieuThem.Rows.Item(i).Cells(7).Value = sListAQuy(i).Gia
        Next
    End Sub

    Function TestData() As Boolean
        If txtMaPin.Text = "" And txtTenPin.Text = "" And txtHangSX.Text = "" And cbLoaiPin.SelectedIndex = -1 And txtCongSuatMin.Text = "" And txtCongSuatMax.Text = "" And txtDienApMax.Text = "" And txtDienApMin.Text = "" And txtGiaMax.Text = "" And txtGiaMin.Text = "" Then
            MsgBox("Không được bỏ trống. Vui lòng kiểm tra lại!", MsgBoxStyle.Exclamation, "Thông báo lỗi")
            txtMaPin.Focus()
            Return False
        End If
        Return True
    End Function

    Public Sub Export_To_Exel(ByVal _DataSet As DataTable, ByVal _List_Col As String, ByVal Path As String)
        '- _Dataset: lưu dữu liệu cần Export
        '- _List_Col: Danh sách tên cột hiển thị. Tên cột cách nhau dấu ','
        '- Path: Đường dẫn lưu file excel
        Dim col, row As Integer
        Dim arrListcol() As String
        arrListcol = _List_Col.Split(",")

        If _DataSet.Rows.Count <= 0 Then
            Exit Sub
        End If

        Dim Excel As Object = CreateObject("Excel.Application")
        If Excel Is Nothing Then
            MessageBox.Show("Để xuất ra Excel, máy bạn phải cài đặt bộ phần mềm Microsoft Office.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Return
        End If

        'Export to Excel process
        Try
            With Excel
                .SheetsInNewWorkbook = 1
                .Workbooks.Add()
                .Worksheets(1).Select()

                Dim i As Integer = 2
                .cells(1, 3).value = "Date:" + Format(Now, "MMM-dd-yyyy")
                .cells(2, i).value = "No"
                .cells(2, i).EntireRow.Font.Bold = True
                For col = 0 To arrListcol.Length - 1
                    i += 1
                    .cells(2, i).value = arrListcol(col).ToUpper()
                    .cells(2, i).EntireRow.Font.Name = "Times New Roman"
                    .cells(2, i).EntireRow.Font.Size = 10
                    .cells(2, i).EntireRow.Font.Bold = True
                Next
                i = 3
                Dim k As Integer = 3

                For col = 0 To _DataSet.Columns.Count - 1
                    i = 3
                    For row = 0 To _DataSet.Rows.Count - 1
                        .Cells(i, 2).Value = i - 2
                        .Cells(i, k).Value = _DataSet.Rows(row).ItemArray(col)
                        i += 1
                    Next
                    k += 1
                Next
                .Columns.AutoFit()
                .ActiveCell.Worksheet.SaveAs(Path)
            End With
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
            Excel = Nothing
            MessageBox.Show("Xuất dữ liệu thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)

            Dim proc As System.Diagnostics.Process
            For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
                proc.Kill()
            Next

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Public Sub AddList(ByVal sListSelect As IList(Of Integer))
        For i As Integer = 0 To sListSelect.Count - 1
            aqController = New AcQuyBUS()
            Dim j As Integer = Val(sListSelect.Item(i))
            sListAQuy.AddRange(aqController.SelectById(j))
        Next
    End Sub

    '------------------------------------------------------'
    '                 Các Hàm Xử Lý Chính               '
    '------------------------------------------------------'
    Private Sub btnThoat_Click(sender As Object, e As EventArgs) Handles btnThoat.Click
        Me.Close()
    End Sub

    Private Sub frmTraCuuAcQuy_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        cbLoaiPin.Items.Clear()
        Dim dt As New DataTable
        aqController = New AcQuyBUS()
        Dim sListlaq As New List(Of LoaiAcquyDTO)
        dt = aqController.LoadComboListbox()
        If dt.Rows.Count > 0 Then
            cbLoaiPin.DataSource = dt
            cbLoaiPin.ValueMember = "MaLoai"
            cbLoaiPin.DisplayMember = "TenLoai"
        End If
        cbLoaiPin.SelectedIndex = -1
        LockText(True)
        BlockButton(btnSua, btnXoa, 1)
    End Sub

    Private Sub cbNangCao_CheckedChanged(sender As Object, e As EventArgs) Handles cbNangCao.CheckedChanged
        If cbNangCao.Checked = True Then
            LockText(False)
        Else
            LockText(True)
        End If

    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles cbChinhSua.CheckedChanged
        If cbChinhSua.Checked = True Then
            BlockButton(btnSua, btnXoa, 0)
        Else
            BlockButton(btnSua, btnXoa, 1)
        End If

    End Sub

    Private Sub btnNhapLai_Click(sender As Object, e As EventArgs) Handles btnNhapLai.Click
        ReSet()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        aqController = New AcQuyBUS()
        sListAQuy = aqController.GetData()
        LoadGrid()
        ReSet()
    End Sub

    Private Sub btnTimKiem_Click(sender As Object, e As EventArgs) Handles btnTimKiem.Click
        Dim MAcQuy As Integer = Val(txtMaPin.Text)
        Dim TAcQuy As String = txtTenPin.Text
        Dim MLoai As Integer = cbLoaiPin.SelectedValue
        Dim HSX As String = txtHangSX.Text
        Dim DDienMin As Single = Val(txtCongSuatMin.Text)
        Dim DDienMax As Single = Val(txtCongSuatMax.Text)
        Dim DApMin As Single = Val(txtDienApMin.Text)
        Dim DApMax As Single = Val(txtDienApMax.Text)
        Dim GiaMin As Integer = Val(txtGiaMin.Text)
        Dim GiaMax As Integer = Val(txtGiaMax.Text)
        If TestData() = True Then
            _aq = New AcquyDTO(MAcQuy, TAcQuy, MLoai, HSX, DDienMin, DDienMax, DApMin, DApMax, GiaMin, GiaMax)
            aqController = New AcQuyBUS()
            sListAQuy = aqController.TimKiem(_aq)
            If sListAQuy.Count() <= 0 Then
                MsgBox("Không tìm thấy kết quả!")
                sListAQuy.Clear()
            End If
            LoadGrid()
        End If
    End Sub

    Private Sub dgvDuLieuThem_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvDuLieuThem.CellContentClick

        'sListAQuySelect.Add(dgvDuLieuThem.Rows.Item(i).Cells(0).Value)
    End Sub

    Private Sub btnXoa_Click(sender As Object, e As EventArgs) Handles btnXoa.Click
        Dim qs = MsgBox("Bạn chắc chắn muốn xóa tất cả thông tin ", vbInformation + vbYesNo, "Thông báo")
        For Each i As DataGridViewRow In dgvDuLieuThem.SelectedRows
            Dim j As Integer = Integer.Parse(i.Cells(0).Value.ToString())
            sListAQuySelect.Add(j)
        Next
        If qs = vbYes Then
            If sListAQuySelect.Count > 0 Then
                For j As Integer = 0 To sListAQuySelect.Count - 1
                    aqController.DeleteProduct(sListAQuySelect.Item(j))
                Next
                MsgBox("Dữ liệu đã xóa thành công", vbInformation, "Thông báo")
                aqController = New AcQuyBUS()
                sListAQuy = aqController.GetData()
                LoadGrid()
            End If
        Else
            MsgBox("Đã hủy thao tác xóa!", vbExclamation, "Thông báo")
        End If
    End Sub

    Private Sub btnSua_Click(sender As Object, e As EventArgs) Handles btnSua.Click
        For Each i As DataGridViewRow In dgvDuLieuThem.SelectedRows
            Dim j As Integer = Integer.Parse(i.Cells(0).Value.ToString())
            sListAQuySelect.Add(j)
        Next
        If sListAQuySelect.Count > 0 Then
            frmLuuAcquy.AddList(sListAQuySelect)
            frmLuuAcquy.MdiParent = Me.MdiParent
            frmLuuAcquy.Show()

            LoadGrid()
            sListAQuySelect.Clear()
        Else
            MsgBox("Bạn chưa chọn!", vbExclamation, "Thông báo")
        End If
    End Sub

    Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
        dataAcQuy = New DataTable()
        dataAcQuy.Columns.Add("MaAcQuy", GetType(String))
        dataAcQuy.Columns.Add("TenAcQuy", GetType(String))
        dataAcQuy.Columns.Add("HangSanXuat", GetType(String))
        dataAcQuy.Columns.Add("TenLoai", GetType(String))
        dataAcQuy.Columns.Add("DongDien", GetType(String))
        dataAcQuy.Columns.Add("DienAp", GetType(String))
        dataAcQuy.Columns.Add("Gia", GetType(String))
        For i As Integer = 0 To Me.dgvDuLieuThem.RowCount - 1
            Dim dr As DataRow = dataAcQuy.NewRow
            Dim hoangvu As String = dgvDuLieuThem.Rows.Item(i).Cells(2).Value.ToString
            dr("MaAcQuy") = dgvDuLieuThem.Rows.Item(i).Cells(0).Value.ToString
            dr("TenAcQuy") = dgvDuLieuThem.Rows.Item(i).Cells(1).Value.ToString
            dr("TenLoai") = dgvDuLieuThem.Rows.Item(i).Cells(3).Value.ToString
            dr("HangSanXuat") = dgvDuLieuThem.Rows.Item(i).Cells(2).Value.ToString
            dr("DongDien") = dgvDuLieuThem.Rows.Item(i).Cells(5).Value.ToString
            dr("DienAp") = dgvDuLieuThem.Rows.Item(i).Cells(6).Value.ToString
            dr("Gia") = dgvDuLieuThem.Rows.Item(i).Cells(7).Value.ToString
            dataAcQuy.Rows.Add(dr)
        Next
        Try
            SaveFileExcel.Filter = "Excel (*.xls)|*.xls"
            SaveFileExcel.ShowDialog()
            Dim File_name = SaveFileExcel.FileName
            Export_To_Exel(dataAcQuy, "Mã Ác Quy,Tên Ác Quy,Hãng Sản Xuất,Loại,Dòng Điện, Điện Áp,Giá", File_name)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub dgvDuLieuThem_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDuLieuThem.CellClick

    End Sub
    Dim MyDataGridViewPrinter As DataGridViewPrinter
    Private Function SetupThePrinting() As Boolean
        If PrintDialog.ShowDialog() <> DialogResult.OK Then
            Return False
        End If

        PrintDocument.DocumentName = "Các Hệ Thống Điện Năng Lượng Mặt Trời Phù Hợp"
        PrintDocument.PrinterSettings = PrintDialog.PrinterSettings
        PrintDocument.DefaultPageSettings = PrintDialog.PrinterSettings.DefaultPageSettings
        PrintDocument.DefaultPageSettings.Margins = New Margins(40, 40, 40, 40)

        If MessageBox.Show("Canh chính giữa trang?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            MyDataGridViewPrinter = New DataGridViewPrinter(dgvDuLieuThem, PrintDocument, True, True, "Các Hệ Thống Điện Năng Lượng Mặt Trời Phù Hợp", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
        Else
            MyDataGridViewPrinter = New DataGridViewPrinter(dgvDuLieuThem, PrintDocument, False, True, "Customers", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
        End If
        Return True
    End Function

    Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.Click
        'PrintPreviewDialog1.Document = PrintDocument1
        'PrintDocument1.DefaultPageSettings.Landscape = True
        'PrintPreviewDialog1.ShowDialog()
        If SetupThePrinting() Then
            PrintDocument.Print()
        End If

    End Sub

    Private Sub btnXemTruoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXemTruoc.Click
        If SetupThePrinting() Then
            PrintPreviewDialog.Document = PrintDocument
            PrintPreviewDialog.ShowDialog()
        End If
    End Sub

    Private Sub PrintDocument_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument.PrintPage
        Dim more As Boolean = MyDataGridViewPrinter.DrawDataGridView(e.Graphics)
        If more = True Then
            e.HasMorePages = True
        End If
    End Sub
End Class